//
//  GAOComposeController.swift
//  Weibo28
//
//  Created by 高辰 on 16/5/19.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD

@available(iOS 9.0, *)
class GAOComposeController: UIViewController, UITextViewDelegate {
    
    //  MARK: 懒加载控件
    //导航栏右侧按钮
    private lazy var rightButton: UIButton = {
        let button = UIButton()
        button.setTitle("发送", forState: .Normal)
        button.titleLabel?.font = UIFont.systemFontOfSize(15)
        //文字颜色
        button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        button.setTitleColor(UIColor.grayColor(), forState: .Disabled)
        //背景图片
        button.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        button.bounds = CGRect(x: 0, y: 0, width: 45, height: 30)
        //添加点击事件
        button.addTarget(self, action: "sendAction", forControlEvents: .TouchUpInside)
        return button
    }()
    
    //自定义导航栏头标题
    private lazy var titleLabel: UILabel = {
        let label = UILabel(textColor: UIColor.darkGrayColor(), fontSize: 17)
        
        if let name = GAOUserAccountViewModel.UserAccountViewModel.userAccount?.name {
            //设置label的副文本
            let text: String = "发微博\n\(name)"
            let attributedStr = NSMutableAttributedString(string: text)
            //取到name的Range
            let range = (text as NSString).rangeOfString(name)
            //修改颜色
            attributedStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range: range)
            //修改字体大小
            attributedStr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(15), range: range)
            label.attributedText = attributedStr
            
        }else {
            label.text = "发微博"
        }
        
        label.numberOfLines = 0
        label.textAlignment = .Center
        label.sizeToFit()
        return label
    }()
    
    
    private lazy var textView: GAOComposeTextView = {
        let view = GAOComposeTextView()
        //设置代理
        view.delegate = self
        view.placeholder = "分享点新鲜事..."
        view.font = UIFont.systemFontOfSize(15)
        //  垂直方向能够滚动
        view.alwaysBounceVertical = true
        return view
    }()
    
    private lazy var toolBar: GAOComposeToolBar = {
        let view = GAOComposeToolBar(frame: CGRectZero)
        return view
    }()
    
    private lazy var pictureView: GAOComposePictureView = {
        let pictureView = GAOComposePictureView()
        pictureView.backgroundColor = self.view.backgroundColor
        return pictureView
    }()
    //自定义表情键盘
    private lazy var emoticonKeyboard: GAOEmoticonKeyboard = {
        let view = GAOEmoticonKeyboard()
        view.size = CGSize(width: self.textView.width , height: 216)
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        
        //  监听键盘改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChageFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        //  监听点击表情按钮的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "didSelectedEmoticonAction:", name: DidSeletedEmoticonNotification, object: nil)
        //  监听点击删除按钮的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "deleteEmoticonButtonAction", name: DeleteEmoticonButtonNotification, object: nil)
        
        
        toolBar.didSeletedButtonClosure = {  [weak self] (type: ToolBarButtonType) in
            switch type {
            case .Picture:
                print("Picture")
                //  选择图库
                self?.didSelectedPicture()
                
            case .Mention:
                print("Mention")
            case .Trend:
                print("Trend")
            case .Emoticon:
                print("Emoticon")
                //  表情键盘
                self?.didSelectedEmoticon()
            case .Add:
                print("Add")
            }
        }
        
        //点击图片的加号按钮回调
        pictureView.didSelectAddImageClosure = { [weak self] in
            self?.didSelectedPicture()
        }
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    private func setupUI() {
        view.backgroundColor = UIColor.whiteColor()
        
        setupNavUI()
        view.addSubview(textView)
        view.addSubview(toolBar)
        view.addSubview(pictureView)
        //  设置约束
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(view)
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.bottom.equalTo(toolBar.snp_top)
        }
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view)
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.height.equalTo(44)
        }
        
        pictureView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView).offset(100)
            make.centerX.equalTo(textView)
            make.width.equalTo(textView).offset(-20)
            make.height.equalTo(textView.snp_width).offset(-20)
        }
        
    }
    
    //设置导航栏视图
    private func setupNavUI() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", fontSize: 15, target: self, action: "cancelAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        //设置rightBarButtonItem默认不可用
        navigationItem.rightBarButtonItem?.enabled = false
        
        navigationItem.titleView = titleLabel
    }
    
    //取消按钮点击事件
    @objc private func cancelAction() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    //发送按钮点击事件
    @objc private func sendAction() {
               //  发送的带有图片的微博
        if pictureView.images.count > 0 {
            
                //   准备参数
                let accesstoken = GAOUserAccountViewModel.UserAccountViewModel.accessToken!
                let status = textView.emticonText!
                
                SVProgressHUD.show()
                
                //  调用发图片微博接口
                let image = pictureView.images.first!
                
                GAONetworkTools.NetworkTools.requsetUpload(accesstoken, status: status, image: image, callBack: { (response, error) -> () in
                    if error != nil {
                        SVProgressHUD.showErrorWithStatus("网络异常")
                        return
                    }
                    
                    SVProgressHUD.showSuccessWithStatus("发送成功")
                })
        
        }else {
            let accesstoken = GAOUserAccountViewModel.UserAccountViewModel.accessToken!
            let status = textView.emticonText!
            
            // 请求发送微博的接口
            GAONetworkTools.NetworkTools.requsetUpdate(accesstoken, status: status) { (response, error) -> () in
                if error != nil {
                    SVProgressHUD.showErrorWithStatus("网络异常")
                    return
                }
                SVProgressHUD.showSuccessWithStatus("发送成功")
                
            }
        }
        
        
    }
    
    //  MARK:   -键盘监听事件
    @objc private func keyboardChageFrame(noti: NSNotification) {
        //        print(noti.userInfo)
        
        let keyboardFrame = (noti.userInfo!["UIKeyboardFrameEndUserInfoKey"]! as! NSValue).CGRectValue()
        
        //        print(keyboardFrame)
        let animationDuration = (noti.userInfo!["UIKeyboardAnimationDurationUserInfoKey"]! as! NSNumber).doubleValue
        //        print(animationDuration)
        
        
        //  更新约束
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(keyboardFrame.origin.y - view.frame.size.height)
        }
        
        UIView.animateWithDuration(animationDuration) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
    }
    
    @objc private func didSelectedEmoticonAction(notice: NSNotification) {
        guard let emoticonData = notice.object as? GAOEmoticonModel else {
            return
        }
        
        textView.insertEmoticon(emoticonData, font: textView.font!)
    }
    
    @objc private func deleteEmoticonButtonAction() {
        //  删除textview内容
        textView.deleteBackward()
    }
    
    
    
    
    // 滑动textView时结束编辑
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        self.view.endEditing(true)
    }
    
    
    //  MARK: <UITextViewDelegate>
    
    func textViewDidChange(textView: UITextView) {
        //textView有值时令rightBarButtonItem的状态改为enabled
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
    deinit {
        //  移除通知
        NSNotificationCenter.defaultCenter().removeObserver(self)
        print("over")
    }
}


extension GAOComposeController: UINavigationControllerDelegate, UIImagePickerControllerDelegate {
    //  点击表情的操作
    func didSelectedEmoticon() {
        //  设置表情键盘视图
        //  当inputView是nil时代表当前为系统键盘
        if textView.inputView == nil {
            //  切换为表情键盘
            textView.inputView = emoticonKeyboard
            //  改变表情按钮icon
            toolBar.changeEmotionIcon(true)
        }else {
            //  切换为系统键盘
            textView.inputView = nil
            //  改变表情按钮icon
            toolBar.changeEmotionIcon(false)
        }
        //获取第一响应者
        textView.becomeFirstResponder()
        //重新加载自定义的inputView
        textView.reloadInputViews()
        
    }
    
    
    //点击图片的操作
    func didSelectedPicture() {
        let pictureVc = UIImagePickerController()
        
        pictureVc.delegate = self
        
        //  是否支持这种类型
        if UIImagePickerController.isSourceTypeAvailable(.Camera) {
            pictureVc.sourceType = .Camera
        } else {
            pictureVc.sourceType = .PhotoLibrary
        }
        
        // 判断前置摄像头是否可用
        if UIImagePickerController.isCameraDeviceAvailable(.Front) {
            print("前置摄像头可用")
        } else if UIImagePickerController.isCameraDeviceAvailable(.Rear) {
            print("后置摄像头可用")
        } else {
            print("摄像头不可用")
        }
        //  可用编辑
        //        pictureVc.allowsEditing = true
        
        presentViewController(pictureVc, animated: true, completion: nil)
        
        
        
    }
    
    //  UIImagePickerControllerDelegate 实现代理方法
    //  实现了代理方法后,要自己调用dismiss
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
//        print(image)
        //压缩图片
        let scaleImage = image.scaleImageWithWidth(300)
        pictureView.addImage(scaleImage)
        
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
}

